package com.car.service;

import com.car.mapper.CustomerMapper;
import com.car.vo.StatisticsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计服务
 *
 * @author Car System
 */
@Service
@RequiredArgsConstructor
public class StatisticsService {

    private final VehicleService vehicleService;
    private final CustomerMapper customerMapper;
    private final MaintenanceRecordService maintenanceRecordService;
    private final RepairRecordService repairRecordService;

    /**
     * 获取统计数据
     */
    public StatisticsVO getStatistics() {
        StatisticsVO vo = new StatisticsVO();

        // 基础统计
        vo.setTotalVehicles(vehicleService.count());
        vo.setTotalCustomers(customerMapper.selectCount(null));
        vo.setMonthMaintenanceCount(maintenanceRecordService.countThisMonth());
        vo.setMonthRepairCount(repairRecordService.countThisMonth());
        vo.setMonthMaintenanceCost(maintenanceRecordService.sumCostThisMonth());
        vo.setMonthRepairCost(repairRecordService.sumCostThisMonth());

        // 月度保养趋势（最近6个月）
        List<Map<String, Object>> maintenanceTrend = maintenanceRecordService.getMonthlyStatistics(6);
        vo.setMaintenanceTrend(maintenanceTrend);

        // 月度维修趋势（最近6个月）
        List<Map<String, Object>> repairTrend = repairRecordService.getMonthlyStatistics(6);
        vo.setRepairTrend(repairTrend);

        // 费用分布数据
        List<Map<String, Object>> costDistribution = new ArrayList<>();
        
        BigDecimal maintenanceCost = vo.getMonthMaintenanceCost() != null ? 
                vo.getMonthMaintenanceCost() : BigDecimal.ZERO;
        BigDecimal repairCost = vo.getMonthRepairCost() != null ? 
                vo.getMonthRepairCost() : BigDecimal.ZERO;
        
        Map<String, Object> maintenance = new HashMap<>();
        maintenance.put("type", "保养费用");
        maintenance.put("value", maintenanceCost);
        costDistribution.add(maintenance);
        
        Map<String, Object> repair = new HashMap<>();
        repair.put("type", "维修费用");
        repair.put("value", repairCost);
        costDistribution.add(repair);
        
        vo.setCostDistribution(costDistribution);

        return vo;
    }
}

